package com.maas.util.mybatis.jpa.littlenb.support.template.select;

import com.littlenb.mybatisjpa.support.template.SqlTemplate;
import com.littlenb.mybatisjpa.util.PersistentUtil;
import com.maas.util.mybatis.jpa.littlenb.common.JpaTools;
import org.apache.ibatis.jdbc.SQL;


import javax.persistence.Column;
import java.lang.reflect.Field;

/**
 * @author sway.li
 **/
public class SelectSqlTemplate implements SqlTemplate {

  public static final SelectSqlTemplate INSTANCE = new SelectSqlTemplate();



  /**
   * 查询 的字段
   */
  public  String selectParm = "";


  public static boolean selectable(Field field) {
    if (!PersistentUtil.isPersistentField(field) || PersistentUtil.isAssociationField(field)) {
      return false;
    }

    if (field.isAnnotationPresent(Column.class)) {
      Column column = field.getAnnotation(Column.class);
      return column.insertable();
    }

    return true;
  }

  @Override
  public String parseSQL(final Class<?> type) {
    return new SQL() {
      {
        String columns ="";
        if(JpaTools.isNotEmpty(selectParm)){
          columns =selectParm;
        }else {
          for (Field field : PersistentUtil.getPersistentFields(type)) {
            if (selectable(field)) {
//            SET(PersistentUtil.getColumnName(field) + " = " + ColumnMetaResolver
//                .resolveSqlPlaceholder(field));
              columns += "p." + PersistentUtil.getColumnName(field)+",";
            }
          }
          columns =JpaTools.cutOffLastStr(columns,",");
        }

        SELECT(columns);
        FROM(PersistentUtil.getTableName(type) +" p");
      }
    }.toString();
  }

}
